<template>
    <div class="questionnaire">

        <div class="position-line"></div>

        <div class="question-box">

            <div :class="['progress' ,'ceiling' , fixed ?  'topfixed' :''] ">
                <el-progress :percentage="percentage" :show-text="false"></el-progress>
            </div>

            <!-- <div class="title">
                问卷标题
            </div> -->

            <div class="tips">
                尊敬的用户感谢您在百忙之中参与此次调查。本次调查主要为了了解您对{{CONFIG_PROJECT.title}}的使用情况及满意度，
                我们非常重视每位用户的宝贵意见，请将您的宝贵意见或建议告知我们，以便我们及时改进，更好地为您服务。谢谢！
            </div>

            <div class="question-list">
                <!-- 单选类型 -->
                <!-- 单选，+ input输入框 -->
                <!-- 多选，+input输入框 -->
                <!-- 问题，答案，选中以后的返回值。 -->

                <div class="question-item" v-for="(item,index) in  questionList" :key="index">
                    <div class="item-postion" :id="item.id"></div>

                    <div v-if="item.type ==='radio'">
                        <qradio v-model="item.answer" :serialNum="index+1" :data="item"></qradio>
                    </div>

                    <div v-if="item.type ==='radio-button'">
                        <qradio type='radioButton' v-model="item.answer" :serialNum="index+1" :data="item">
                            <div slot="tips2" class="tips2">
                                <div>非常不满意</div>
                                <div>非常满意</div>
                            </div>
                        </qradio>
                    </div>

                    <div v-if="item.type ==='checkbox-input'">
                        <qcheckboxInput v-model="item.answer" :serialNum="index+1" :data="item" @otherItem="item.otherFun"></qcheckboxInput>
                    </div>

                    <div v-if="item.type ==='radio-input'" class="radio-input">
                        <qradioInput v-model="item.answer" :serialNum="index+1" :data="item" @otherItem="item.otherFun"></qradioInput>
                    </div>

                    <div v-if="item.type ==='textarea'">
                        <qtextarea v-model="item.answer" :serialNum="index+1" :data="item"></qtextarea>
                    </div>

                </div>

            </div>

            <div class="bottom">
                <el-button type="primary" @click="onSubmit">提交</el-button>
            </div>

        </div>
    </div>
</template>

<script>
import CONFIG_PROJECT from '@config/project';

import qradio from './components/q-radio.vue';
import qcheckboxInput from './components/q-checkbox-input.vue';
import qradioInput from './components/q-radio-input.vue';
import qtextarea from './components/q-textarea.vue';

export default {
    name: '',
    components: { qradio, qcheckboxInput, qradioInput, qtextarea },
    data() {
        return {
            CONFIG_PROJECT,
            
            questionList: [
                {
                    question: `您是通过什么途径获悉的${CONFIG_PROJECT.title}？`,
                    answerList: ['朋友邀请', '广告宣传', '社群推荐', '工具下载'],
                    answer: '',
                    type: 'radio', //radio (radio-button) , radio-input , checkbox-input ,
                    id: '01', //定位 id
                    isMust: true, //是否必填
                },
                {
                    question: `您每周多长时间打开一次${CONFIG_PROJECT.title}？`,
                    answerList: ['每天打开一次', '2-3天打开一次', '3-4天打开一次', '4-5天打开一次', '6-7天打开一次'],
                    answer: '',
                    type: 'radio',
                    id: '02',
                    isMust: true,
                },
                {
                    question: `您使用${CONFIG_PROJECT.title}最多的功能有哪些？`,
                    answerList: ['网站导航', '标讯', '企业画像', '投标方案下载', '投标方案在线制作', '商机人脉', '数据报表', '数据统计', '其他'],
                    answer: [],
                    type: 'checkbox-input',
                    id: '03',
                    isMust: true,
                    tips: '最多选三个',
                    otherItem: '', // 接收用户输入input框里的内容
                    otherFun: (val) => {
                        //赋值
                        this.questionList[2].otherItem = val;
                    },
                },
                {
                    question: '你用过其他类似的网站吗？',
                    answerList: ['没有', '有'],
                    answer: '',
                    type: 'radio-input',
                    id: '04',
                    isMust: true,
                    tips: '如果有，烦请写出网站名称',
                    otherItem: '',
                    otherFun: (val) => {
                        this.questionList[3].otherItem = val;
                    },
                },
                {
                    question: `请您为${CONFIG_PROJECT.title}打分`,
                    answerList: ['1', '2', '3', '4', '5'],
                    answer: '',
                    type: 'radio-button',
                    id: '05',
                    isMust: true,
                    tips: '5分表示非常满意，1分表示非常不满意，分值越低表示满意度越低',
                },
                {
                    question: `您会向朋友推荐${CONFIG_PROJECT.title}吗？`,
                    answerList: ['十分愿意', '不太愿意', '不愿意'],
                    answer: '',
                    type: 'radio',
                    id: '06',
                    isMust: true,
                    tips: '',
                },
                {
                    question: '说说您的具体感受？帮助我们为您和其他用户提供更好的服务。',
                    answerList: [],
                    answer: '',
                    type: 'textarea',
                    id: '07',
                    isMust: true,
                    tips: '',
                },
            ],

            otherItem3: '',
            otherItem4: '',
            wb: '',
            ceilingRight: null,
            isLogin: null,
            fixed: false,
        };
    },
    computed: {
        percentage() {
            let nums = 0;
            this.questionList.forEach((item, index) => {
                if (item.answer.length > 0) {
                    nums++;
                }
            });

            return (nums / this.questionList.length) * 100;
        },
    },
    mounted() {
        this.checkLoginHandler();
    },
    methods: {
        //怕判断是否 填写完全。必填？
        inspectIsMust() {
            let isHaveNoWrite = false;
            /* 4.使用 try catch */
            try {
                this.questionList.forEach((item) => {
                    if (item.isMust && item.answer.length == 0) {
                        isHaveNoWrite = true;
                        document.getElementById(`${item.id}`).scrollIntoView();
                        this.fixedActiveLine();
                        this.$message({
                            type: 'warning',
                            message: `还有尚未填写的内容，请填写完成后，再提交`,
                        });

                        throw '终止循环'; // 抛出一个异常
                    }
                });
            } catch (e) {
                console.log('catch内容：' + e); // catch内容：终止循环
            }

            return isHaveNoWrite;
        },

        onSubmit() {
            if (this.isLogin == false) {
                this.$message({
                    type: 'warning',
                    message: `请您登录后再提交问卷`,
                });
                this.$store.dispatch('global-dialog/showLogin');
                return;
            }

            if (this.inspectIsMust()) {
                return;
            }

            let parmas = '';
            let url = JSON.stringify(this.parseQueryString(window.location.search));
            this.questionList.forEach((item, index) => {
                let answer = item.otherItem ? item.answer + '&nbsp;' + item.otherItem : item.answer;
                parmas = `${parmas} <b><p>${index + 1} ${item.question}</p></b><p>${answer}</p> <br>`;
            });
            this.$post(
                `${this.$store.state.api.tbUrl}/question/fill.json`,
                {
                    content: parmas,
                    url: url,
                },
                (data) => {
                    if (data === '提交成功!') {
                        this.$message({
                            type: 'success',
                            message: `提交成功`,
                        });
                        window.location.replace('/questionnaire/replace')
                    } else {
                        this.$message({
                            message: `${data}`,
                        });
                    }
                }
            );
        },

        // 判断是否登录
        checkLoginHandler() {
            this.$store.dispatch('userinfo/checkIsLoginNoDoing', {
                login: () => {
                    this.isLogin = true;
                },
                noLogin: () => {
                    this.isLogin = false;
                    this.$message({
                        type: 'warning',
                        message: `请您登录后再填写问卷`,
                    });

                    // 打开登录弹窗
                    this.$store.dispatch('global-dialog/showLogin');
                },
            });
        },

        //转换参数
        parseQueryString(url) {
            if (!url) {
                return;
            }
            url = decodeURIComponent(url);
            var obj = {};
            var params = url.slice(1);
            var arr = params.split('&');
            arr.forEach((v, i) => {
                let str = v.split('=')[1];
                if (str.indexOf('%') === -1) {
                    obj[v.split('=')[0]] = v.split('=')[1];
                } else {
                    obj[v.split('=')[0]] = JSON.parse(decodeURIComponent(v.split('=')[1]));
                }
            });
            return obj;
        },

        fixedActiveLine() {
            let databottom = document.querySelector(`.position-line`);
            if (!databottom) {
                return;
            }

            let toTop = databottom.getBoundingClientRect().top; //距离顶部高度 ;
            this.fixed = toTop < 0;
        },

        // 节流
        throttle(fn, time) {
            let timer = null;
            time = time || 1000;
            return function (...args) {
                if (timer) {
                    return;
                }
                const _this = this;
                timer = setTimeout(() => {
                    timer = null;
                }, time);
                fn.apply(_this, args);
            };
        },
    },
    beforeMount() {
        window.addEventListener('wheel', throttle(this.fixedActiveLine, 100));
    },
    beforeDestroy() {
        window.removeEventListener('wheel', this.fixedActiveLine);
    },
};
</script>

<style lang="scss" scoped>
.questionnaire {
    padding: 20px 0;
    .position-line {
        height: 0;
    }

    .question-box {
        width: 1000px;
        margin: 0 auto;
        padding: 10px 40px;
        background-color: #fff;
        .progress {
            width: 100%;
            padding: 10px 0;
            background-color: #fff;
        }
        .topfixed {
            position: fixed;
            width: 920px;
            top: 0;
            z-index: 99;
        }

        .title {
            text-align: center;
            margin-top: 40px;
            font-size: 30px;
            font-weight: normal;
            word-break: break-word;
        }
        .tips {
            font-size: 16px;
            line-height: 1.6;
            margin: 30px 0;
        }

        .question-item {
            .item-postion {
                position: relative;
                height: 0;
                padding: 0;
                margin: 0;
                border: none;
                bottom: 30px;
            }
        }

        .bottom {
            margin: 20px 0;
            text-align: center;

            .el-button {
                padding: 10px 50px;
            }
        }

        .tips2 {
            width: 310px;
            margin: 20px 0;
            display: flex;
            justify-content: space-between;
            div {
                color: #000;
                background-color: #f2f2f2;
                padding: 2px 5px;
                border-radius: 5px;
            }
        }
    }
}
</style>

